package course

import (
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"io/ioutil"
	"strings"
	"time"
	"yangming-college/app/speciality/cmd/v1/api/internal/svc"
	"yangming-college/app/speciality/cmd/v1/api/internal/types"
	. "yangming-college/common/snowflake"
)

type CreateCourseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateCourseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCourseLogic {
	return &CreateCourseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateCourseLogic) CreateCourse(uid int64, req *types.ReqCearteCourse) error {
	courseDocument := map[string]interface{}{
		"uid":                 uid,
		"title":               req.Title,
		"coverurl":            req.CoverAddress,
		"speciality_tags":     req.SpecialityTags,
		"classification_tags": req.ClassificationTags,
		"customize_tags":      req.CustomizeTags,
		"description":         req.Description,
		"isoriginal":          req.IsOriginal,
		"collection":          0,
		"like":                0,
		"view":                0,
		"score":               0,
		"numscore":            0,
		"updated":             time.Now(),
	}

	courseJSON, err := json.Marshal(courseDocument)
	if err != nil {
		return errors.Wrapf(err, "speciality v1 api CreateCourse error 1")
	}

	reqIndex := esapi.IndexRequest{
		Index:      "course",
		DocumentID: GenSnowflakeStringID(),
		Body:       strings.NewReader(string(courseJSON)),
		Refresh:    "true",
	}

	res, err := reqIndex.Do(context.Background(), l.svcCtx.ESClinet)
	if err != nil {
		return errors.Wrapf(err, "speciality v1 api CreateCourse error 2")
	}
	defer res.Body.Close()

	if res.IsError() {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return errors.Wrap(err, "failed to read response body")
		}

		// Use the body (error details) as needed
		errorMessage := string(body)
		return errors.New(errorMessage)
	}
	return nil
}
